package com.qys.livesMall.financial.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.qys.livesMall.app.user.model.dto.sys.SysUserBalanceChangeDTO;
import com.qys.livesMall.app.user.model.enums.UserBalanceLogTypeEnum;
import com.qys.livesMall.app.user.service.IH2AppUserBalanceService;
import com.qys.livesMall.app.user.service.IH2AppUserService;
import com.qys.livesMall.common.constants.Constants;
import com.qys.livesMall.common.exception.QysException;
import com.qys.livesMall.finance.enums.AccountBusinessTypeEnum;
import com.qys.livesMall.finance.model.dto.FinancePayDTO;
import com.qys.livesMall.finance.service.FinanceBusinessService;
import com.qys.livesMall.financial.model.dto.OnlineSettlementContext;
import com.qys.livesMall.financial.model.dto.UserIncome;
import com.qys.livesMall.financial.model.entity.FinancialOnlineDetail;
import com.qys.livesMall.financial.model.entity.FinancialOnlineSettlementInfo;
import com.qys.livesMall.financial.model.entity.FinancialOnlineUser;
import com.qys.livesMall.financial.service.FinancialOnlineDetailService;
import com.qys.livesMall.financial.service.FinancialOnlineSettlementInfoService;
import com.qys.livesMall.financial.service.FinancialOnlineUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @menu SettlementServer
 * @date 2023/07/26 9:44
 */
@Slf4j
@Component
@AllArgsConstructor
public class SettlementTX {

    private final FinancialOnlineDetailService onlineDetailService;
    private final IH2AppUserService userService;
    private final FinancialOnlineUserService financialOnlineUserService;

    private final FinancialOnlineSettlementInfoService settlementInfoService;

    private final FinanceBusinessService financeBusinessService;

    @Transactional(rollbackFor = Exception.class)
    public void settlement(OnlineSettlementContext context){
        if (!context.isStatus()){
            onlineDetailService.updateById(context.getDetail());
            return;
        }
        //更新明细状态
        LambdaUpdateWrapper<FinancialOnlineUser> uw=new LambdaUpdateWrapper<>();
        uw.set(FinancialOnlineUser::getSettlementStatus, Constants.YesNoInt.YES);
        uw.eq(FinancialOnlineUser::getFinancialOrderId,context.getDetail().getId());
        financialOnlineUserService.update(uw);
        //从平台账户扣除金额用于分配
        if (context.getSettlementInfo().getTotalIncome()!=null) {
            FinancePayDTO payDTO = new FinancePayDTO();
            payDTO.setBusinessNo(context.getDetail().getOrderNo());
            payDTO.setAmountIncurred(context.getSettlementInfo().getTotalIncome());
            payDTO.setBusinessType(AccountBusinessTypeEnum.PRODUCT_INVESTMENT_PROFIT_OUT);
            financeBusinessService.pay(payDTO);
            if (!payDTO.getSuccess()){
                throw new QysException(payDTO.getMessage());
            }
        }


        //结算上级收益
        if (!CollectionUtils.isEmpty(context.getUserIncomes())){
            for (UserIncome income: context.getUserIncomes()){
                if (Objects.equals(income.getUserStatus(), Constants.YesNoInt.NO)){
                    continue;
                }
                FinancePayDTO payDTO = new FinancePayDTO();
                payDTO.setUserId(Long.valueOf(income.getUserId()));
                payDTO.setBusinessNo(context.getDetail().getOrderNo());
                payDTO.setAmountIncurred(income.getIncome());
                payDTO.setBusinessType(AccountBusinessTypeEnum.PRODUCT_INVESTMENT_SUPERIOR_PROFIT_IN);
                financeBusinessService.pay(payDTO);
                if (!payDTO.getSuccess()){
                    throw new QysException(payDTO.getMessage());
                }
            }
        }
        //结算个人收益
        if (context.getSettlementInfo().getIncome()!=null){
            FinancePayDTO payDTO = new FinancePayDTO();
            payDTO.setUserId(Long.valueOf(context.getUserId()));
            payDTO.setBusinessNo(context.getDetail().getOrderNo());
            payDTO.setAmountIncurred(context.getSettlementInfo().getIncome());
            payDTO.setBusinessType(AccountBusinessTypeEnum.PRODUCT_INVESTMENT_PROFIT_IN);
            financeBusinessService.pay(payDTO);
            if (!payDTO.getSuccess()){
                throw new QysException(payDTO.getMessage());
            }
        }

        //结算本金
        if (context.getSettlementInfo().getPrincipal()!=null){
            FinancePayDTO payDTO = new FinancePayDTO();
            payDTO.setUserId(Long.valueOf(context.getUserId()));
            payDTO.setBusinessNo(context.getDetail().getOrderNo());
            payDTO.setAmountIncurred(context.getSettlementInfo().getPrincipal());
            payDTO.setBusinessType(AccountBusinessTypeEnum.PRODUCT_INVESTMENT_PRINCIPAL_RETURN);
            financeBusinessService.pay(payDTO);
            if (!payDTO.getSuccess()){
                throw new QysException(payDTO.getMessage());
            }
        }

        //修改购买状态
        context.getDetail().setReturnPrincipalStatus((byte)1);
        context.getDetail().setStatus((byte)2);
        onlineDetailService.updateById(context.getDetail());

        //保存结算记录
        context.getSettlementInfo().setSettlementDate(LocalDateTime.now());
        settlementInfoService.save(context.getSettlementInfo());

    }


}

